package com.zxc.reggie.service.lmpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxc.reggie.common.R;
import com.zxc.reggie.dto.DishDto;
import com.zxc.reggie.entity.Dish;
import com.zxc.reggie.entity.DishFlavor;
import com.zxc.reggie.mapper.DishMapper;
import com.zxc.reggie.service.DishFlavorService;
import com.zxc.reggie.service.DishService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {


    @Resource
    private DishFlavorService dishFlavorService;


    @Override
    public R<String> savaWithFlavor(DishDto dishDto) {

        save(dishDto);
        Long dishDtoId = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().peek((item) -> item.setDishId(dishDtoId)).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
        return R.success("添加菜品成功");
    }

    @Override
    public R<String> updateWithFlavor(DishDto dishDto) {
        updateById(dishDto);

        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().peek(item -> item.setDishId(dishDto.getId())).collect(Collectors.toList());

        LambdaQueryWrapper<DishFlavor> DishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        DishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(DishFlavorLambdaQueryWrapper);

        dishFlavorService.saveBatch(flavors);
        return R.success("修改成功");
    }
}
